<!--
@Description:新增编辑
@Author:zqy
@Date:2024-10-22 16:15:47
@Last Modified by:zqy
@Last Modified time:2024-10-22 16:15:47
-->
<template>
  <el-dialog
    ref="formDlg"
    :title="`${!!(detail && detail.id)?'编辑':'新增'}弹窗信息`"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="600px"
    @close="closeDialog"
  >
    <div style="padding-right:30px">
      <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="展示平台:" prop="displayTerminal">
              <el-select v-model="formData.displayTerminal" disabled>
                <el-option v-for="(dict,i) in dictList" :key="i" :label="dict.dictName" :value="dict.dictCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="弹窗名称:" prop="name">
              <el-input v-model.trim="formData.name" maxlength="20" show-word-limit placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片内容:" prop="pic">
              <div class="img-upload-container">
                <qup-img-uploader
                  :width="100"
                  :height="100"
                  mask
                  :image-url="cateImage.absoluteUrl"
                  :relative-url="cateImage.relativeUrl"
                  @upload-success="handleUploadSuccess"
                  @remove="handleDelImg"
                />
                <div class="icon-msg">建议图片<!--尺寸大小100*100,-->不超过1M,支持png\jpg\jpeg</div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文字内容:" prop="content">
              <el-input
                v-model="formData.content"
                type="textarea"
                :rows="6"
                maxlength="200"
                show-word-limit
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="有效时间:" prop="beginEndTime">
              <el-date-picker
                v-model="formData.beginEndTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="关联内容:"
              prop="gotoDTO"
            >
              <RelateCategory
                ref="formLink"
                v-model="formData.gotoDTO"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button v-loading="submiting" size="mini" type="primary" @click="submitForm">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { queryDetail, saveConfig } from '@/api/indexPageTip'
import QupImgUploader from '@/components/imgUploader'
import RelateCategory from '@/components/RelateCategoy'
export default {
  name: 'IndexPageTipEdit',
  components: { QupImgUploader, RelateCategory },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      dictList: [
        { dictCode: 'SAD-APP', dictName: '销售宝APP' },
        { dictCode: 'SAD-PAD', dictName: '销售宝PAD' },
        { dictCode: 'SAD-PC', dictName: '销售宝PC' }
      ],
      formData: {
        displayTerminal: 'SAD-APP', // 展示端（SAD-APP、SAD-PAD、SAD-PC）
        name: '',
        pic: '',
        content: '',
        beginEndTime: [],
        gotoDTO: {
          gotoType: '', // 关联类型
          categoryDTOList: [], // 类目ID
          filterId: '', // 商品中心类目模板
          gotoValue: '', // 关联内容值 (帮助中心详情ID，自定义页面ID，商品详情ID)
          gotoName: '' // 内容名称(帮助中心详情，自定义页面，商品详情)
        },
        enableFlag: 1
      },
      formRules: {
        /* code: [
          { required: true, message: '请输入风格编码', trigger: 'blur' },
          { pattern: /^[a-zA-Z\d][\w-]{0,19}$/, message: '输入字母、数字、中划线、下划线' }
        ], */
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        /* pic: [
          { required: true, message: '请上传封面图', trigger: 'change' }
        ] */
        content: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        beginEndTime: [
          { required: true, message: '请选择', trigger: ['blur', 'change'] }
        ]
      },
      cateImage: {
        absoluteUrl: '',
        relativeUrl: ''
      },
      submiting: false
    }
  },

  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    if (this.detail && this.detail.id) {
      queryDetail(this.detail.id).then(res => {
        const data = res.data || {}
        const enableFlag = [0, '0', 1, '1'].includes(data.enableFlag) ? data.enableFlag : 1
        let beginEndTime = []
        const { beginTime, endTime } = this.detail
        if (beginTime && endTime) {
          beginEndTime = [beginTime, endTime]
        }
        this.formData = {
          displayTerminal: data.displayTerminal,
          name: data.name,
          pic: data.pic,
          content: data.content,
          beginEndTime,
          enableFlag,
          gotoDTO: {
            gotoType: data.gotoType || '',
            categoryDTOList: data.categoryDTOList || [],
            filterId: data.filterId || '',
            gotoValue: data.gotoValue || '',
            gotoName: data.gotoName || ''
          }
        }
        this.cateImage = {
          absoluteUrl: this.formatImageUrl(data.pic),
          relativeUrl: data.pic
        }
      })
    }
  },

  methods: {
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    clearForm(done) {
      this.formData = {
        name: '',
        pic: '',
        content: '',
        beginEndTime: [],
        enableFlag: 1,
        gotoDTO: {
          gotoType: '', // 关联类型
          categoryDTOList: [], // 类目ID
          filterId: '', // 商品中心类目模板
          gotoValue: '', // 关联内容值 (帮助中心详情ID，自定义页面ID，商品详情ID)
          gotoName: '' // 内容名称(帮助中心详情，自定义页面，商品详情)
        }
      }
      this.cateImage = {
        absoluteUrl: '',
        relativeUrl: ''
      }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    submitForm(type) {
      if (this.submiting) return
      this.$refs['refForm'].validate(async(valid) => {
        if (valid) {
          const { gotoDTO, beginEndTime } = this.formData
          // 当跳转关联为商品中心类目时,筛选模板必填
          if (gotoDTO.gotoType === 'GOODS_CENTER_CATEGORY') {
            if (!gotoDTO.filterId) {
              this.$message.error('筛选模板必填!')
              return
            }
          }

          let categoryDTOList = []
          if (gotoDTO && gotoDTO.categoryDTOList) {
            categoryDTOList = gotoDTO.categoryDTOList.map(v => {
              return {
                categoryId: v.categoryId,
                categoryName: v.categoryName
              }
            })
          }

          const formData = {
            categoryDTOList,
            ...this.formData,
            ...gotoDTO
          }
          if (this.detail && this.detail.id) {
            formData.id = this.detail.id
          }

          if (beginEndTime && beginEndTime.length === 2) {
            formData.beginTime = beginEndTime[0]
            formData.endTime = beginEndTime[1]
          }
          delete formData.gotoDTO
          delete formData.beginEndTime

          this.submiting = true
          await saveConfig(formData).then(res => {
            this.submiting = false
            if (res.success === 1) {
              this.$message({
                message: `${formData.id ? '编辑' : '新增'}保存成功`,
                type: 'success'
              })
              this.$emit('success', !formData.id)
              this.closeDialog()
            }
          }).catch(() => {
            this.submiting = false
          })
        }
      })
    },
    handleUploadSuccess(res, file, fileList) {
      this.formData.pic = res.storeFileName
      this.cateImage = {
        absoluteUrl: res.url,
        relativeUrl: res.storeFileName
      }
    },
    handleDelImg() {
      this.formData.pic = ''
      this.cateImage = {
        absoluteUrl: '',
        relativeUrl: ''
      }
    }
  }
}
</script>
<style lang='scss' scoped>
  .img-upload-container {
    .icon-msg{
      margin-top: 10px;
      color: #999;
    }
  }
</style>
